/**
 * 公共接口
 *
**/

//ajax
import fetch from 'isomorphic-fetch'

export function myAjax(url, method, param, callback1, callback2) {
	fetch(url, {
		    method: method,
		    headers: {
		      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
		    },
			 body: analysisJson(param)
			})
			.then((response) => {
				if (response.ok) {
				    response.json().then((data) => callback1(data));
				  } else {
				  	callback2(response)
				    console.log("Looks like the response wasn't perfect, got status", response.status);
				  }

			})
			.catch(function (error) {
				callback2(error)
			    console.log('Request failed', error);
			});

}

export function myAjaxJson(url, method, param, callback1, callback2) {
	let token = isLogining();
	fetch(url, {
		    method: method,
		    headers: {
					"X-Cafune-Authentication": "SECRET",
					"X-Cafune-Session-Token": token,
		      "Content-type": "application/json; charset=UTF-8"
		    },
			  body: JSON.stringify(param)
			})
			.then((res) => {
				if (res.ok) {
				    res.json().then((data) => callback1(data));
				  } else {
				  	callback2(res)
				    console.log("Looks like the response wasn't perfect, got status", res.status);
				  }

			})
			.catch(function (error) {
			  	callback2(error)
			    console.log('Request failed', error);
			});
}

//处理返回数据格式非json 格式
export function myAjaxText(url, method, param, callback1, callback2) {
	let token = isLogining();
	fetch(url, {
		    method: method,
		    headers: {
		      "Content-type": "application/json; charset=UTF-8",
					"X-Cafune-Authentication": "SECRET",
				  "X-Cafune-Session-Token": token
		    },
			  body: JSON.stringify(param)
			})
			.then((res) => {
				if (res.ok) {
				    res.text().then((data) => callback1(data));
				  } else {
				  	callback2(res)
				    console.log("Looks like the response wasn't perfect, got status", res.status);
				  }

			})
			.catch(function (error) {
			  	callback2(error)
			    console.log('Request failed', error);
			});

}

//不加头信息
//以json 格式请求数据  ----普通版
export function commonJsonFetch(url, method, param, callback1, callback2) {

            fetch(url, {
                    method: method,
                    headers: {"Content-Type": "application/json; charset=utf-8"},
                    credentials: 'include',
                    body: JSON.stringify(param)
                }).then(function(response) {
                    return response.json()
                }).then(function(json) {
                    if (callback1 && callback1 != '') {
                        callback1(json);
                    }
                }).catch(function(ex) {
                    if (callback2 && callback2 != '') {
                        callback2(ex);
                    }
                })

}


//get 方法不能在body 里面传数据
// export const myAjaxGet = function(url, data, callback1, callback2) {
// 	  let token = isLogining();
//     fetch(url + `?${analysisJson(data)}`,{
// 			headers: {
// 			  	"X-Cafune-Authentication": "SECRET",
//           "X-Cafune-Session-Token": token
// 			}
//     }).then(function(response) {
//         return response.json()
//     }).then(function(json) {
//         if (callback1 && callback1 != '') {
//             callback1(json);
//         }
//     }).catch(function(ex) {
//         if (callback2 && callback2 != '') {
//             callback2(ex);
//         }
//     })
// }

//get方法
export const myAjaxGet = function(url, data, callback1, callback2) {
		let token = isLogining();
		fetch(`${url}?${analysisJson(data)}`,{
			headers: {
				  "Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
					"X-Cafune-Authentication": "SECRET",
					"X-Cafune-Session-Token": token
			}
		})
		.then((res) => {
				if (res.ok) {
						res.json().then((data) => callback1(data));
				} else {
						callback2(res)
						console.log("Looks like the response wasn't perfect, got status", res.status);
				}

		})
		.catch(function (error) {
				callback2(error)
				console.log('Request failed', error);
		});
}

//获取当前登录用户
export const getAdminInfo = function(callback1, callback2) {
		myAjaxGet(`${ROOTURL}user/general/me.api`, '', (data) => {
			  sessionStorage.setItem("adminInfo", JSON.stringify(data))
				if (callback1) callback1(data);
		}, (data) => {
			  if (callback2) callback2(data);
				alert("登陆已过期，或者登陆出错")
        location.href = "/login"
		})
}

/*判断是否登陆
    return    token
*/
let login = JSON.parse(localStorage.getItem("userInfo"));
export const isLogining = function() {
		if (!login) {
			  login = JSON.parse(localStorage.getItem("userInfo"));
		}
		if (!login.token) {
					alert('您还没有登陆')
					location.href = "/login"
		}
		return login.token;
}

/*获取当前用户有权限管辖的门店
  @param
	callback(function): 函数回调  function
	[param(object)]: 调用 shop/search.api 传递的限制，格式和api一样，比如：
	{where: {
			 stActivate: [
					['eq', true]
			]
		 }
		}------->只反回没有启用的门店
*/
let adminShopIds = [];
export const getAuthShop = function(param, callback) {
	  let adminInfo = JSON.parse(sessionStorage.getItem("adminInfo"));
		console.log(adminInfo);
		if (!adminInfo) {
		  	getAdminInfo(() => {
					  getAuthShop(param, callback)
				})
				return;
		}
		if (adminInfo.clazz === REGION_ADMIN) {
			   if (adminShopIds.length <= 0) {
						 myAjaxJson(ROOTURL + 'region/assign/search.api', 'POST', {
							 where:{
									 adminId: [
											 ['eq', adminInfo.id]
									 ]
								 }
						 }, (data) => {
								 data.forEach(function(admin) {
										 adminShopIds.push(admin.shopId);
								 })
	               getShopInfo(adminShopIds, param, callback)
						 }, () => {
								 alert('获取门店失败！');
						 })
				 } else {
             getShopInfo(adminShopIds, param, callback)
				 }
		} else {
         getShopInfo(null, param, callback)
		}
}

//获取门店信息
function getShopInfo(ids, param, callback) {

	  let id = ids? [['in', ids]] : null;
		let regionParam = {
			  where: {
					  dd: [
							  ['eq', false]
						],
						id
				}
		}
		let where = regionParam.where
		if (param) {
			  if (param.where) where = Object.assign(regionParam.where, param.where);
			  regionParam = Object.assign(regionParam, param);
				regionParam.where = where;
		}
		myAjaxJson(ROOTURL + 'shop/search.api', 'POST', regionParam, (data) => {
			  if (callback) {
					  callback(data);
				}
		}, () => {
				alert('获取门店失败！');
		})
}

function analysisJson(obj) {
    let str = ""
    for (let key in obj) {
        str += key + "=" + obj[key] + '&'
    }
    return str.substr(0,str.length - 1);
}

export function http(data,url,callback1,callback2) {
	var xmlhttp;
	function createXHttpRequest() {
		if (window.ActiveXObject) {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		else if (window.XMLHttpRequest) {
			xmlhttp = new XMLHttpRequest();
		}
		else {
			return;
		}
	}

	function starRequest(data) {
		createXHttpRequest();
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				if (xmlhttp.status == 200) {
					callback1();
				}else{
					callback2();
				}
			}
		};
		xmlhttp.open("POST", url, true);
		xmlhttp.send(data);
	}
	starRequest(data);
}

/**
 *  全局变量
 */

export const ROOTURL = 'http://diy1.fashcollege.com/pepper/'
export const ROOTURL_MALL = 'http://diy1.fashcollege.com/diykabuy/'
export const ROOTURL_TABLE = 'http://diy1.fashcollege.com/spearman/'
export const ROOTURL_COMM = 'http://diy1.fashcollege.com/cacomm/'
export const ROOTPATH = ''

//标识管理员 or  局部管理员
export const ADMIN = '.admn'   //--->管理员
export const REGION_ADMIN = '.radm'    //-->区域管理员
export const SHOP_ADMIN = "shopadmin"

/**
* 公用函数
*/
//动态生成路径

export function DynPath(route) {

	return ROOTPATH+route;
}
